﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Core
{
    public class UITabBar : UIWidget
    {
        [UIField("")]
        private readonly UITile<UITab> grid;

        private readonly List<string> tabNames = new();
        private readonly List<string> tabKeys = new();
        private readonly List<UIWidget> widgets = new();

        private UITab currTab;
        private UIWidget currView;

        public int Index { get; private set; }

        public event Action<int> OnValueChanged;

        public override void Awake(GameObject go)
        {
            base.Awake(go);

            tabNames.Clear();
            tabKeys.Clear();

            grid.SetUpdateFunc(OnUpdateHandler);
            grid.SetSelectFunc(OnSelectHandler);

        }

        private void OnUpdateHandler(UITab tab, int index)
        {
            tab.SetOn(false);
            tab.SetText(tabNames[index]);
            if (index >= 0 && index < tabKeys.Count)
            {
                tab.gameObject.name = $"Tab_{tabKeys[index]}";
            }
        }

        private void OnSelectHandler(UITab tab, int index)
        {
            currTab?.SetOn(false);
            currTab = tab;
            currTab?.SetOn(true);

            Index = index;

            SelectView(index);

            OnValueChanged?.Invoke(index);
        }

        public void SetTabs(List<string> names, List<string> keys = null)
        {
            tabNames.Clear();
            tabNames.AddRange(names);

            tabKeys.Clear();
            if (keys != null)
            {
                tabKeys.AddRange(keys);
            }

            grid.SetAmount(tabNames.Count);
        }

        public void SetViews(IReadOnlyList<object> widgets)
        {
            this.widgets.Clear();
            currView = null;
            foreach (var obj in widgets)
            {
                if (obj is UIWidget w)
                {
                    this.widgets.Add(w);
                    w.SetActive(false);
                }
            }
        }

        public void Select(int index)
        {
            if (index < 0 || index >= grid.Count) return;

            currTab?.SetOn(false);
            currTab = grid.GetChildAt(index);
            currTab.SetOn(true);
            Index = index;

            SelectView(index);

            OnValueChanged?.Invoke(index);
        }

        private void SelectView(int index)
        {
            if (index < 0 || index >= widgets.Count)
            {
                return;
            }

            if (currView == widgets[index])
            {
                return;
            }

            currView?.SetActive(false);
            currView = widgets[index];
            currView?.SetActive(true);
        }
    }
}
